package com.company.project.service.impl;

import com.company.project.core.Result;
import com.company.project.core.ResultGenerator;
import com.company.project.dao.SysRoleAuthMapper;
import com.company.project.dao.SysRoleMapper;
import com.company.project.model.SysFunctionTreeDto;
import com.company.project.model.SysRole;
import com.company.project.model.SysRoleAuth;
import com.company.project.service.SysRoleAuthService;
import com.company.project.core.AbstractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;


/**
 * Created by CodeGenerator on 2020/04/18.
 */
@Service
@Transactional
public class SysRoleAuthServiceImpl extends AbstractService<SysRoleAuth> implements SysRoleAuthService {
    @Resource
    private SysRoleAuthMapper sysRoleAuthMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;

    /**
     * 根据用户ID查询角色列表
     *
     * @param userId
     * @return
     */
    @Override
    public Result queryRoleListTreeByUser(int userId) {
        List<SysRole> roleList = sysRoleMapper.getRoleListByUser(userId);
        List<SysFunctionTreeDto> childrenTree = getChildrenTree(roleList);
        return ResultGenerator.genSuccessResult(childrenTree);
    }

    private List<SysFunctionTreeDto> getChildrenTree(List<SysRole> roleList){
        List<SysRole> roles = sysRoleMapper.selectAll();
        if (null == roles || roles.size() == 0){
            return null;
        }else {
            HashSet<Integer> set = new HashSet<Integer>();
            if (null != roleList && roleList.size() >0){
                //判断是否被选中
                for (SysRole role : roleList) {
                    set.add(role.getId());
                }
            }
            List<SysFunctionTreeDto> functionList = new ArrayList<>();
            for (SysRole role : roles) {
                SysFunctionTreeDto sysFunctionTreeDto = new SysFunctionTreeDto();
                sysFunctionTreeDto.setKey(role.getId());
                sysFunctionTreeDto.setLabel(role.getRoleName());
                sysFunctionTreeDto.setSpread(false);
                sysFunctionTreeDto.setChecked(false);
                if (set.contains(role.getId())){
                    sysFunctionTreeDto.setChecked(true);
                }
                functionList.add(sysFunctionTreeDto);
            }
            return functionList;
        }

    }
}
